﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using Microsoft.Xna.Framework.Graphics;
using System.Xml;

namespace Jemgine.MapEditor.Operations
{
	internal class Import : Operation
	{
        bool NeedsLoading = false;
        string MapName;
        List<Data.MapElement> PreImport;
        Data.MapData Map = null;

        internal Import(string MapName)
        {
            this.MapName = MapName;
            NeedsLoading = true;
        }

        internal Import(Data.MapData Data)
        {
            this.Map = new Data.MapData(Data);
            NeedsLoading = false;
        }

        internal override ReturnCode Do(EditorState ES)
        {
            PreImport = new List<Jemgine.Data.MapElement>(ES.Map.Elements);

            try
            {
                if (NeedsLoading)
                {
                    XmlReader Reader = XmlReader.Create(MapName);
                    Map = IntermediateSerializer.Deserialize<Jemgine.Data.MapData>(Reader, MapName);
                    Reader.Close();
                }

                String MapDirectory = System.IO.Path.GetDirectoryName(MapName);

                Map.PostProcess(null, Vector2.Zero, null);

                ES.SelectItem(Jemgine.Engine.Selection.None);
                ES.MultiSelection.Clear();

                foreach (var MapElement in Map.Elements)
                {
                    ES.Map.Elements.Add(MapElement);
                    ES.MultiSelection.Add(new Jemgine.Engine.Selection(Jemgine.Engine.Selection.Types.MapElement,
                        ES.Map.Elements.Count - 1, 0, 0));

                    ES._RebuildTree();
                }

                return ReturnCode.AddToUndoStack;
            }
            catch (Exception e)
            {
                ES.OnConsoleOutput(e.Message);
            }

            return ReturnCode.DoNotAddToUndoStack;
        }

		internal override void Undo(EditorState ES)
		{
            ES.Map.Elements = PreImport;
            ES.SelectItem(Jemgine.Engine.Selection.None);
            ES.MultiSelection.Clear();
		}
	}
}
